package com.ias.agdis_r.util;

import java.security.MessageDigest;
import java.util.HashMap;
import java.util.Map;

import com.ias.agdis_r.manager.JavaBeanManager;
import com.ias.agdis_r.module.ParameterModel;
import com.ias.agdis_r.terminalmanager.restful.base.endpoint.request.BaseRequestHeader;

import android.util.Base64;

public class SecurityUtil {

	private SecurityUtil() {
	}

	public static String getToken(String userId, String channelId, String serviceId) {

		StringBuffer sb = new StringBuffer();
		sb.append(userId);
		sb.append(channelId);
		sb.append(serviceId);

		MessageDigest msgDigest;
		try {
			msgDigest = MessageDigest.getInstance("SHA-1");
			byte[] hashedBytes = msgDigest.digest(sb.toString().getBytes("UTF-8"));
			return Base64.encodeToString(hashedBytes, Base64.DEFAULT).replace("\n", "");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return "";
	}

	public static String getToken(String serviceID) {
		if (serviceID == null) {
			serviceID = "";
		}
		String userid = JavaBeanManager.getInstance().getUserinfo().getEnb();
		String channelId = ParameterModel.IMEI_ID;
		return getToken(userid, channelId, serviceID);
	}

	/**
	 * 得到一个没有密码的Header
	 * 
	 * @param serviceId
	 * @return
	 */
	public static Map<String, String> getCommonRequestHeader(String serviceId) {
		if (serviceId == null) {
			serviceId = "";
		}

		// TODO 用户没登陆处理
		if (S.isEmpty(JavaBeanManager.getInstance().getUserinfo().getEnb())) {
			JavaBeanManager.getInstance().getUserinfo().setEnb("");
		}

		String token = getToken(JavaBeanManager.getInstance().getUserinfo().getEnb(), ParameterModel.IMEI_ID,
				serviceId);

		Map<String, String> header = new HashMap<String, String>();
		header.put("channelId", ParameterModel.IMEI_ID);
		header.put("serviceId", serviceId);
		header.put("userId", JavaBeanManager.getInstance().getUserinfo().getEnb());
		header.put("token", token);
		return header;
	}

	/**
	 * 得到一个没有密码的BaseRequestHeader
	 * 
	 * @param serviceId
	 * @return
	 */
	public static BaseRequestHeader getCommonRequestHeaderObject(String serviceId) {

		if (serviceId == null) {
			serviceId = "";
		}

		// TODO 用户没登陆处理
		if (S.isEmpty(JavaBeanManager.getInstance().getUserinfo().getEnb())) {
			JavaBeanManager.getInstance().getUserinfo().setEnb("");
		}

		BaseRequestHeader header = new BaseRequestHeader();

		header.setChannelId(ParameterModel.IMEI_ID);
		header.setUserId(JavaBeanManager.getInstance().getUserinfo().getEnb());
		header.setServiceId(serviceId);

		header.setToken(getToken(header.getUserId(), header.getChannelId(), header.getServiceId()));

		return header;
	}

}
